package com.zlc.gulimall.product.exception;

import com.zlc.common.exception.BizCodeEnume;
import com.zlc.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;


@Slf4j
@RestControllerAdvice
public class GulimallExceptionControllerAdvice {

    @ExceptionHandler
    public R handleValidException(MethodArgumentNotValidException e) {
        log.info("数据校验异常:{}", e.getMessage());
        BindingResult result = e.getBindingResult();

        HashMap<String, String> map = new HashMap<>();
        //获取错误信息
        result.getFieldErrors().forEach((item) -> {
            //获取到错误信息
            String message = item.getDefaultMessage();
            //获取到错误字段
            String field = item.getField();
            map.put(field, message);
        });

        return R.error(BizCodeEnume.VALID_EXCEPTION.getCode(), BizCodeEnume.VALID_EXCEPTION.getMessage())
                .put("data", map);
    }

    @ExceptionHandler
    public R handleAll(Exception e){
        return R.error(e.getMessage());
    }
}
